var conversationsListView;
var composeView;
var conversationViews = [];

$().ready(function(){
	app.bindEvents();
});
ComposeView = function(){
	this.recipients = [];
	this.onLoad = function(){
		var self = this;
		$(this.element).find('ul').filterList({
			caseInsensitive: true,
			cbFunc: function(elem, val, caseInsensitive){
				elem = $(elem).filter('label').text();
				return caseInsensitive ? elem.toLowerCase().indexOf(val.toLowerCase()) !== -1 : elem.indexOf(val) !== -1;
			},
			callback : function(){
				self.scrollers[0].scrollToTop();
			},
			filterWrapper: $('.address-input').parent()[0]
		});
		$(this.element).find('input').prop('checked',false);
		$(this.element).find('.recipients').html('');
		this.recipients = [];

		$('#composeButton').hide();

		$('#addRecipientButton').bind('click',function(){
			var address = $('.address-input').val();
			if(!address || address.length == 0) return;
			//if(address != NaN){
				/** Problem... NaN != NaN yields true.. so NaN(not a number) is not equal to NaN(itself)..
				 *  Also typeof NaN yields 'number'.. so NaN(not a number) is of type 'number'...
				*/
			//	var recipient = app.ContactsControl.findBy("address",address);
				self.addRecipient({name:'',address:address});
			//}
			/*else{
				$('.content').growl({
					message: 'Μπορείτε να εισάγετε έναν αριθμό τηλεφώνου ή όνομα επαφής ως παραλήπτη',
					title : '',
					timeout: 2000
				})
			}*/
		});
	};
	this.onUnload = function(){
		$('#composeButton').show();
	};

	this.onCheckboxChange = function(checkbox){
		var recipientsDiv = $('.recipients');
		var contactIndex = checkbox.getAttribute('data-index');
		var contact = app.ContactsControl.contacts[contactIndex];

		if(checkbox.checked)
			this.addRecipient(contact,contactIndex);
		else{
			this.removeRecipient(recipientsDiv,contactIndex);
		}
	};
	this.addRecipient = function(recipient,index){		
		if(recipient.name == '' || index == undefined){
			var contactIndex = app.ContactsControl.indexOf(recipient.address);
			if(contactIndex != -1)
				index = contactIndex;
			else {
				contactIndex = app.ContactsControl.indexOf(recipient.address,"name");
				if(contactIndex != -1){
					index = contactIndex;
					recipient.name = recipient.address;
					recipient.address = app.ContactsControl.contacts[contactIndex].address;
				}
			}
		}
		if(this.findRecipientBy("address",recipient.address) != undefined ) return;

		if(index == undefined) index = new Date().getTime();

		var recipientsDiv = $('.recipients');
		var elem = $('<span data-index="'+index+'"class="recipient">'+((recipient.name!='')?recipient.name:recipient.address)+'</span>');
		var self = this;

		$('#contact-'+index).prop('checked',true);
		elem.one('click',function(){
			$(this).addClass('removable icon-cross');
			$(this).one('click',function(){
				var index = this.getAttribute('data-index');
				self.removeRecipient(recipientsDiv,index);
				$('#contact-'+index).prop('checked',false);
			});
		});

		recipientsDiv.append(elem);
		this.recipients.push($.extend(recipient,{index:index}));

		this.scrollers[1].scrollToBottom();
	};
	this.removeRecipient = function(recipientsDiv,index){
		var el = recipientsDiv.find('.recipient[data-index="'+index+'"]');
		if(el.index() == 0)
			this.scrollers[1].scrollToTop();
		else
			this.scrollers[1].scrollToItem(el.siblings().get(el.index()-1));

		el.remove();
		for(var i=0;i<this.recipients.length;i++){
			if(this.recipients[i].index == index){
				this.recipients.splice(i,1);
			}
		}

	};
	this.findRecipientBy = function(field,value){
		for(key in this.recipients){
			if(this.recipients[key][field] == value)
				return this.recipients[key];
		}
	};

	$.extend(this,new PanelView($('#UI>.content'),$('#contactsListTmpl').html()));

	return this;
}
ConversationView = function(){
	$.extend(this,new PanelView($('#UI>.content'),$('#conversationTmpl').html()));

	this.appendMesages = function(messages){
		//TODO
	}
	this.prependMesages = function(messages){
		//TODO
	}
	return this;
}
$.ui.autoLaunch = false;
// $.ui.splashScreenTimeout = 0;
var app = {
	WebServices: {
		AccountBalance:{
			check: function(){
				var username = document.getElementById('usernameField').value;
				var password = document.getElementById('passwordField').value;

				var url = 'http://www.liveall.eu/webservice/sms/getAccountBalance.php?username='+username+'&password='+password;
				$.get(url,function(data){
					if(data.indexOf("1000")!=-1){
						window.localStorage.setItem('username',username);
						window.localStorage.setItem('password',password);
						app.userSettings = {
							username: username,
							password: password
						};
						app.store.set("userSettings",app.userSettings);

						console.log(app.userSettings.username);
						console.log(app.userSettings.password);
						console.log(app.store.get("userSettings").username);
						console.log(app.store.get("userSettings").password);
						alert("Grats!");
					}
					else{
						alert(data);
					}
				});

			},
			onSuccess : function(){

			},
			onError : function(){

			}
		}
	},
	ContactsControl : {
		contacts: [
					{
						"name": "Taylor",
						"address": "873-462-32666"
					},
					{
						"name": "Allison",
						"address": "804-467-35425"
					},
					{
						"name": "Marchya",
						"address": "899-464-34107"
					},
					{
						"name": "Sydney",
						"address": "842-467-26122"
					},
					{
						"name": "Addison",
						"address": "868-560-28445"
					},
					{
						"name": "Gabrielle",
						"address": "801-542-36389"
					},
					{
						"name": "Kimberly",
						"address": "843-429-36074"
					},
					{
						"name": "Morgan",
						"address": "868-482-35693"
					},
					{
						"name": "Madison",
						"address": "823-590-32847"
					}
				],
		initialize : function(){
			//test just for android for now
			if($.os.android){
				var self = this;
				function onSuccess(cts) {
					if(cts){
						self.contacts = [];
						for (var i=0; i<cts.length; i++) {
							if(cts[i].phoneNumbers && cts[i].phoneNumbers.length!=0){
								for (var j=0; j<cts[i].phoneNumbers.length; j++) {
										self.contacts.push({
											name: cts[i].displayName,
											address: cts[i].phoneNumbers[j].value,
											type: cts[i].phoneNumbers[j].type
										});
								}
							}
						}

						self.sort();
						
						if(app.ConversationsControl.state == "ready"){
							app.ConversationsControl.crossWithContacts();
							$(document).trigger('model:ready');
						}
						else self.state = "ready";
					}
				}
				function onError(contactError) {
					alert('onError!');
				}

				var options = new ContactFindOptions();
				options.filter="";
				options.multiple = true;
				var fields = ["displayName", "name","phoneNumbers"];
				navigator.contacts.find(fields, onSuccess, onError, options);
			}
		},
		sort : function(order,by){
			if(!by)
				by = "name";
			if(!order || order=="asc")
				order = 1;
			else
				order = -1;

			this.contacts.sort(function(a,b){
				if(a[by].toLowerCase()<b[by].toLowerCase())
					return -order;
				else if(a[by].toLowerCase()>b[by].toLowerCase())
					return order;
				else return 0;
			});
		},
		findBy : function(by,value){
			if(!value) return undefined;
			if(!by) by ="address";
			for(var i=0;i<this.contacts.length;i++){
				if(this.contacts[i][by] == value)
					return this.contacts[i];
			}
		},
		indexOf : function(value,by){
			if(!value) return -1;
			if(!by) by ="address";
			for(var i=0;i<this.contacts.length;i++){
				if(this.contacts[i][by] == value)
					return i;
			}
			return -1;
		}
	},
	ConversationsControl : {
		conversations : [
			{
				"name": "Taylor",
				"address": "873-462-32666",
				"messages": [
					{
						"message": "Lorem anim veniam aliqua proident nulla fugiat nisi ad officia",
						"date": new Date("09.01.88"),
						"user": "true"
					},
					{
						"message": "occaecat excepteur amet ex eu aliquip tempor eu veniam ex",
						"date": new Date("06.06.04"),
						"user": "true"
					},
					{
						"message": "et ea dolor nostrud tempor dolore ut veniam cupidatat ipsum",
						"date": new Date("22.04.08"),
						
					},
					{
						"message": "nulla sint dolor cillum eiusmod non ea cillum cillum est",
						"date": new Date("21.12.91"),
						"user": "true"
					},
					{
						"message": "ipsum eiusmod et eiusmod ullamco voluptate sint non fugiat irure",
						"date": new Date("27.08.90"),
						"user": "true"
					},
					{
						"message": "sint tempor nostrud cupidatat eiusmod nostrud sunt sunt pariatur consequat",
						"date": new Date("10.01.09"),
						"user": "true"
					},
					{
						"message": "adipisicing velit officia pariatur laborum nostrud anim ut do dolor",
						"date": new Date("23.02.02"),
						
					},
					{
						"message": "dolore anim labore esse et sit ea ad veniam eiusmod",
						"date": new Date("16.02.13"),
						
					},
					{
						"message": "et qui culpa dolor in labore fugiat excepteur nulla non",
						"date": new Date("29.05.06"),
						"user": "true"
					}
				]
			},
			{
				"name": "Emma",
				"address": "802-401-35644",
				"messages": [
					{
						"message": "culpa eu excepteur commodo non nostrud mollit culpa voluptate ad",
						"date": new Date("08.10.03"),
						"user": "true"
					},
					{
						"message": "ad deserunt labore in ad consectetur nulla mollit mollit do",
						"date": new Date("18.12.03"),
						
					},
					{
						"message": "enim eu do sit ut aliqua labore excepteur voluptate id",
						"date": new Date("02.12.93"),
						
					},
					{
						"message": "incididunt duis fugiat in in ipsum ullamco irure elit labore",
						"date": new Date("16.09.02"),
						"user": "true"
					},
					{
						"message": "nisi labore est pariatur excepteur culpa anim officia nisi in",
						"date": new Date("11.01.03"),
						
					},
					{
						"message": "qui dolore nulla consectetur consequat esse amet cillum esse ullamco",
						"date": new Date("06.08.96"),
						
					},
					{
						"message": "labore aliquip eu sit quis ea ullamco sint incididunt eiusmod",
						"date": new Date("31.03.12"),
						
					},
					{
						"message": "dolor aliquip sint voluptate elit elit ad excepteur enim exercitation",
						"date": new Date("12.07.99"),
						"user": "true"
					},
					{
						"message": "irure sunt ea deserunt consectetur irure ea proident sint enim",
						"date": new Date("16.06.95"),
						
					},
					{
						"message": "sit sit enim eu est non elit ullamco incididunt dolor",
						"date": new Date("01.06.08"),
						"user": "true"
					},
					{
						"message": "mollit in veniam aute et aute anim culpa eu dolore",
						"date": new Date("25.12.92"),
						
					},
					{
						"message": "anim excepteur id aute ullamco velit elit dolor in aliquip",
						"date": new Date("24.05.07"),
						
					}
				]
			},
			{
				"name": "Allison",
				"address": "804-467-35425",
				"messages": [
					{
						"message": "est ea ipsum reprehenderit commodo anim adipisicing occaecat magna aliqua",
						"date": new Date("12.11.03"),
						"user": "true"
					},
					{
						"message": "commodo minim mollit adipisicing officia dolore culpa est consectetur qui",
						"date": new Date("12.10.96"),
						"user": "true"
					},
					{
						"message": "ullamco deserunt et deserunt tempor commodo ipsum elit aliqua adipisicing",
						"date": new Date("19.09.91"),
						"user": "true"
					},
					{
						"message": "sint consectetur ad voluptate do incididunt ex mollit duis quis",
						"date": new Date("05.06.09"),
						"user": "true"
					},
					{
						"message": "do cupidatat amet nostrud proident anim laboris aliqua incididunt ex",
						"date": new Date("05.08.02"),
						"user": "true"
					},
					{
						"message": "sunt aliquip pariatur veniam consectetur velit tempor elit ipsum officia",
						"date": new Date("09.07.05"),
						
					},
					{
						"message": "ex sint adipisicing sit et consequat cupidatat quis do labore",
						"date": new Date("07.01.92"),
						"user": "true"
					},
					{
						"message": "nisi exercitation cupidatat pariatur aliqua consequat sint sunt mollit laboris",
						"date": new Date("20.12.94"),
						
					},
					{
						"message": "aliqua reprehenderit anim velit labore ipsum do enim fugiat sint",
						"date": new Date("06.11.06"),
						
					},
					{
						"message": "ex enim ex officia laboris fugiat fugiat commodo nulla ut",
						"date": new Date("23.11.12"),
						"user": "true"
					},
					{
						"message": "do ex eiusmod eu velit laborum irure cillum culpa cillum",
						"date": new Date("01.11.91"),
						
					},
					{
						"message": "laboris minim exercitation et aute enim do aliqua dolore cupidatat",
						"date": new Date("28.11.02"),
						
					}
				]
			},
			{
				"name": "Maya",
				"address": "899-464-34107",
				"messages": [
					{
						"message": "cupidatat laboris velit do est sit ipsum velit nulla enim",
						"date": new Date("06.03.99"),
						"user": "true"
					},
					{
						"message": "quis quis labore proident pariatur ullamco deserunt occaecat laborum et",
						"date": new Date("21.06.07"),
						"user": "true"
					},
					{
						"message": "aliqua laboris culpa aliquip qui adipisicing proident aliquip commodo laborum",
						"date": new Date("22.09.99"),
						"user": "true"
					},
					{
						"message": "magna proident nostrud laboris excepteur consectetur cupidatat sunt ad anim",
						"date": new Date("30.12.96"),
						"user": "true"
					},
					{
						"message": "voluptate ea excepteur Lorem nisi exercitation occaecat tempor enim sit",
						"date": new Date("25.05.08"),
						"user": "true"
					},
					{
						"message": "deserunt laborum anim commodo nisi laboris laborum tempor ullamco et",
						"date": new Date("10.05.95"),
						
					},
					{
						"message": "laboris enim cupidatat proident sunt incididunt elit commodo consectetur laboris",
						"date": new Date("07.03.04"),
						
					},
					{
						"message": "consequat adipisicing nostrud elit est officia nostrud veniam sint id",
						"date": new Date("17.11.03"),
						"user": "true"
					},
					{
						"message": "aute ipsum amet do aute nostrud duis ullamco sint elit",
						"date": new Date("14.11.06"),
						"user": "true"
					},
					{
						"message": "nulla fugiat elit adipisicing culpa elit aliquip minim irure velit",
						"date": new Date("27.03.01"),
						"user": "true"
					},
					{
						"message": "esse aliquip labore minim in deserunt nisi reprehenderit tempor nostrud",
						"date": new Date("02.03.89"),
						"user": "true"
					}
				]
			},
			{
				"name": "Sydney",
				"address": "842-467-26122",
				"messages": [
					{
						"message": "magna proident non minim sit tempor tempor veniam voluptate proident",
						"date": new Date("28.03.06"),
						
					},
					{
						"message": "in cillum commodo cillum laboris aliqua cillum labore irure fugiat",
						"date": new Date("31.03.03"),
						
					},
					{
						"message": "sit sint nostrud minim dolor do ad incididunt tempor velit",
						"date": new Date("30.05.88"),
						"user": "true"
					},
					{
						"message": "voluptate non nisi id proident ipsum enim sunt labore veniam",
						"date": new Date("16.10.93"),
						"user": "true"
					},
					{
						"message": "eiusmod nisi pariatur deserunt duis duis labore cupidatat labore qui",
						"date": new Date("04.03.04"),
						
					},
					{
						"message": "deserunt qui magna sint cupidatat dolore eiusmod mollit officia reprehenderit",
						"date": new Date("24.01.06"),
						"user": "true"
					},
					{
						"message": "aliquip sunt consectetur voluptate aliqua occaecat mollit ut dolor consectetur",
						"date": new Date("30.03.97"),
						"user": "true"
					},
					{
						"message": "amet dolor mollit aliqua nisi anim tempor dolor amet anim",
						"date": new Date("10.12.90"),
						"user": "true"
					},
					{
						"message": "sint excepteur tempor anim ea minim ut aliqua cillum sit",
						"date": new Date("11.03.90"),
						
					}
				]
			},
			{
				"name": "Addison",
				"address": "868-560-28445",
				"messages": [
					{
						"message": "eu elit reprehenderit deserunt magna enim laborum deserunt deserunt ex",
						"date": new Date("19.05.12"),
						"user": "true"
					},
					{
						"message": "enim commodo nisi ex deserunt anim esse cupidatat Lorem anim",
						"date": new Date("04.09.10"),
						
					},
					{
						"message": "nulla eiusmod aute esse incididunt occaecat amet adipisicing adipisicing in",
						"date": new Date("07.02.01"),
						"user": "true"
					},
					{
						"message": "eu consequat proident consectetur laborum cillum irure elit consequat dolor",
						"date": new Date("20.06.97"),
						
					},
					{
						"message": "voluptate reprehenderit consectetur sint fugiat sint sunt aliquip quis culpa",
						"date": new Date("30.11.90"),
						
					},
					{
						"message": "consectetur eiusmod nulla sunt amet irure amet labore veniam non",
						"date": new Date("30.01.07"),
						
					},
					{
						"message": "ut laboris minim fugiat sunt est in Lorem proident aliqua",
						"date": new Date("07.12.98"),
						
					},
					{
						"message": "ipsum commodo non in ea reprehenderit ullamco do elit anim",
						"date": new Date("10.09.93"),
						
					},
					{
						"message": "mollit minim quis aliquip officia nulla enim non id consectetur",
						"date": new Date("18.04.08"),
						
					},
					{
						"message": "occaecat minim aute incididunt aliqua exercitation aute labore cupidatat sunt",
						"date": new Date("19.04.10"),
						"user": "true"
					},
					{
						"message": "velit in fugiat sit ipsum esse ad id eu sint",
						"date": new Date("01.01.12"),
						"user": "true"
					},
					{
						"message": "dolor mollit laboris irure occaecat non enim veniam eu tempor",
						"date": new Date("03.10.03"),
						
					}
				]
			},
			{
				"name": "Gabrielle",
				"address": "801-542-36389",		
				"messages": [
					{
						"message": "proident cupidatat sunt do elit incididunt pariatur do consectetur in",
						"date": new Date("13.03.00"),
						"user": "true"
					},
					{
						"message": "laboris ex ex occaecat eiusmod ea aliquip consectetur culpa ad",
						"date": new Date("22.05.92"),
						"user": "true"
					},
					{
						"message": "commodo in labore non cillum nisi labore do minim nulla",
						"date": new Date("01.10.08"),
						
					},
					{
						"message": "officia sint Lorem veniam commodo duis et officia sunt incididunt",
						"date": new Date("28.10.09"),
						"user": "true"
					},
					{
						"message": "quis ut nulla excepteur occaecat ex officia anim aliquip incididunt",
						"date": new Date("21.06.89"),
						"user": "true"
					},
					{
						"message": "excepteur sint reprehenderit dolor incididunt qui id non quis cillum",
						"date": new Date("12.07.05"),
						"user": "true"
					},
					{
						"message": "reprehenderit aute tempor enim nulla enim et consectetur anim quis",
						"date": new Date("09.09.11"),
						"user": "true"
					},
					{
						"message": "magna ex commodo id commodo ex mollit minim veniam aliqua",
						"date": new Date("24.10.12"),
						
					},
					{
						"message": "qui fugiat irure mollit irure ullamco velit Lorem enim commodo",
						"date": new Date("30.01.02"),
						"user": "true"
					},
					{
						"message": "consectetur eu ullamco laboris reprehenderit id velit magna mollit consequat",
						"date": new Date("20.06.91"),
						"user": "true"
					}
				]
			},
			{
				"name": "Kimberly",
				"address": "843-429-36074",
				"messages": [
					{
						"message": "eiusmod eu fugiat commodo et irure amet sit ex dolore",
						"date": new Date("07.02.04"),
						"user": "true"
					},
					{
						"message": "pariatur culpa ea ea aliqua aliqua occaecat officia dolor aute",
						"date": new Date("06.04.97"),
						"user": "true"
					},
					{
						"message": "ipsum laborum enim est minim officia amet et reprehenderit minim",
						"date": new Date("10.05.03"),
						
					},
					{
						"message": "ut ad mollit consectetur nisi do magna reprehenderit sit dolore",
						"date": new Date("20.08.03"),
						"user": "true"
					},
					{
						"message": "commodo elit sint ullamco commodo nulla proident reprehenderit aliquip culpa",
						"date": new Date("23.06.02"),
						
					},
					{
						"message": "consequat duis pariatur aliquip duis ipsum fugiat officia ex mollit",
						"date": new Date("23.05.13"),
						
					},
					{
						"message": "sint dolor irure adipisicing do aute duis laboris esse ipsum",
						"date": new Date("04.12.88"),
						
					},
					{
						"message": "Lorem velit esse quis ullamco laborum eiusmod duis dolor deserunt",
						"date": new Date("15.11.03"),
						
					},
					{
						"message": "in eiusmod esse consequat deserunt fugiat deserunt ut officia in",
						"date": new Date("10.04.08"),
						"user": "true"
					},
					{
						"message": "irure mollit duis voluptate labore deserunt elit exercitation esse eu",
						"date": new Date("10.12.04"),
						
					},
					{
						"message": "sint proident in et non id tempor officia veniam et",
						"date": new Date("06.03.97"),
						
					}
				]
			},
			{
				"name": "Morgan",
				"address": "868-482-35693",
				"messages": [
					{
						"message": "do anim veniam excepteur tempor tempor enim excepteur aliquip anim",
						"date": new Date("01.02.00"),
						"user": "true"
					},
					{
						"message": "fugiat minim pariatur deserunt reprehenderit veniam consequat labore non magna",
						"date": new Date("09.04.00"),
						
					},
					{
						"message": "excepteur in id cillum aliqua occaecat sit laborum fugiat commodo",
						"date": new Date("04.01.07"),
						
					},
					{
						"message": "aute ullamco anim anim ipsum in aute quis laborum elit",
						"date": new Date("02.05.04"),
						
					},
					{
						"message": "deserunt aute pariatur ea esse dolor sit velit amet sunt",
						"date": new Date("03.02.07"),
						
					},
					{
						"message": "duis occaecat commodo consectetur cillum qui adipisicing consectetur sunt ut",
						"date": new Date("15.12.11"),
						
					},
					{
						"message": "ullamco ullamco sint irure nisi in quis enim adipisicing minim",
						"date": new Date("06.02.95"),
						
					},
					{
						"message": "dolore consectetur quis laboris amet dolore consectetur laborum in dolor",
						"date": new Date("28.10.04"),
						"user": "true"
					},
					{
						"message": "sit quis quis fugiat et pariatur voluptate cupidatat elit eiusmod",
						"date": new Date("11.12.00"),
						"user": "true"
					},
					{
						"message": "duis qui pariatur duis irure voluptate fugiat velit excepteur ad",
						"date": new Date("11.06.97"),
						"user": "true"
					},
					{
						"message": "pariatur cupidatat veniam occaecat commodo id anim est minim aliquip",
						"date": new Date("25.06.10"),
						
					},
					{
						"message": "Lorem ullamco minim velit nulla adipisicing nisi duis adipisicing aliquip",
						"date": new Date("17.10.03"),
						"user": "true"
					}
				]
			},
			{
				"name": "Madison",
				"address": "823-590-32847",
				"messages": [
					{
						"message": "adipisicing laborum aliqua ea Lorem reprehenderit reprehenderit commodo id ex",
						"date": new Date("17.07.90"),
						
					},
					{
						"message": "magna sint voluptate nostrud fugiat aliquip elit ad adipisicing ex",
						"date": new Date("17.02.05"),
						
					},
					{
						"message": "magna sunt quis commodo nulla exercitation sit do duis consequat",
						"date": new Date("29.06.07"),
						"user": "true"
					},
					{
						"message": "nulla cillum nisi aliquip mollit nostrud adipisicing est officia culpa",
						"date": new Date("07.08.01"),
						"user": "true"
					},
					{
						"message": "nisi dolore voluptate tempor sunt sint laborum commodo velit est",
						"date": new Date("18.02.89"),
						"user": "true"
					},
					{
						"message": "amet aliquip nisi fugiat nulla dolore sint reprehenderit dolor enim",
						"date": new Date("30.12.08"),
						"user": "true"
					},
					{
						"message": "est commodo veniam incididunt aute laborum adipisicing cupidatat esse ad",
						"date": new Date("13.01.90"),
						"user": "true"
					},
					{
						"message": "consequat minim mollit dolor ipsum et do do magna duis",
						"date": new Date("02.04.03"),
						"user": "true"
					},
					{
						"message": "ullamco incididunt dolor fugiat incididunt ad labore ipsum tempor sit",
						"date": new Date("16.05.98"),
						"user": "true"
					},
					{
						"message": "amet nostrud occaecat aliquip deserunt minim est sit excepteur anim",
						"date": new Date("31.07.92"),
						"user": "true"
					}
				]
			}
		],
		initialize : function(){
			var readSms = cordova.require("cordova/plugin/readsmsplugin");

			var rangeOpts = {
				sort:"desc",
				from: 0,
				to: 25
			}
			var options={
				address:"",	
				range:rangeOpts
			}

			this.conversations =[];

			var self = this;
			readSms.read(options,function(result) {
				self.conversations = result;
				//TODO: merge native conversations with the liveall.eu ones
				if(app.ContactsControl.state=="ready"){
					self.crossWithContacts();
					$(document).trigger('model:ready');
				}
				else self.state = "ready";
			}, function(error) {
				console.log(error);
			});
		},
		crossWithContacts : function(){
			for(var i=0;i<this.conversations.length;i++){
				var contact = app.ContactsControl.findBy("address",this.conversations[i].address);
				if(contact!=undefined){
					this.conversations[i].name = contact.name;
				}
			}
		}
	},
	intializePanels : function(){
		var conversations = this.ConversationsControl.conversations;

		conversationsListView = new PanelView($('#UI>.content'),$('#conversationsListTmpl').html()).render(conversations,{id:"conversationsList",class:"shown"});
		composeView = new ComposeView();
		composeView.render(this.ContactsControl.contacts,{
			id:'compose',
			onLoad:'composeView.onLoad',
			onUnload:'composeView.onUnload',
			scrollable:false});
		composeView.scrollers = [];
		$(composeView.element).find('.scrollable').forEach(function(el){
			composeView.scrollers.push($(el).scroller());
		});
		

		var content = $('#UI .content');

		for(var i=0;i<conversations.length;i++){
			var panelID = 'conversation-'+i;

			conversationViews[i] = new ConversationView();
			conversationViews[i].render(conversations[i],{scrollable:false,id:panelID,class:"conversation"});
			conversationViews[i].scroller = $(conversationViews[i].element).find('.scrollable').scroller();
		}
		
		$('#UI .contact').bind('click',function(){
			 if(conversationsListView.scroller && !conversationsListView.scroller.moved){
				var conversationIndex = this.getAttribute('data-index');
				$.ui.showPanel('#conversation-'+conversationIndex,'fade');
				conversationViews[conversationIndex].scroller.scrollToBottom();
			 }
		});
	},
	initializeUI : function(){
		this.intializePanels();

		$.ui.launch();

		$(window).bind( 'resize',function(){
			$.ui.refresh();
		});

	},
	bindEvents : function(){
		if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
			console.log('Using mobile');
			var self = this;
			document.addEventListener("deviceready", function(){
				self.onDeviceReady();
			}, false);
		} 
		else {
			console.log('Using desktop');
			$.ui.splashScreenTimeout = 0;
			this.onDeviceReady(); //this is the browser
		}
	},
	onDeviceReady : function(){
		app.store = new LocalStore();
		
		app.userSettings = app.store.get('userSettings');
		var self = this;
		$(document).bind('model:ready',function(){
			self.initializeUI();
		});

		$.ui.ready(function(){
			console.log('ui is ready');
			alert(self.userSettings);
			console.log(self.userSettings);

			FastClick.attach(document.getElementById('UI'));

			if(!app.userSettings){
				$.ui.showMenu();
				self.showLoginForm();
				var el = $('.menu .menu-link')[0];
				el.addEventListener('click',function(){
					self.toggleLoginForm();
				});
			}
			else {
				var el = $('.menu .menu-link')[0];
				el.addEventListener('click',function(){
					self.toggleProfileInfo();
				});

			}

			//Testing
			$('.reply-btn').bind('click',function(){
				$.ui.showPanel('#conversationsList');
				$('.content').growl({message:'Μήνυμα στάληκε επιτυχώς προς: <b style="text-decoration:underline">('+$(this).data('address')+')</b>',title:'Επιτυχής αποστολή',timeout:2500});
			});

			$('#loginButton').bind('click',function(){
				self.WebServices.AccountBalance.check();
				$.ui.hideMenu();
				app.hideLoginForm();
			});
			if(!self.checkConnection()){
				$('#UI').growl({
					message : 'Χρειάζεστε σύνδεση στο ίντερνετ για την αποστολή sms μέσω της υπηρεσίας LiveAll.eu!',
					title : 'Δεν υπάρχει σύνδεση'
				});
			}
		});
		
		if($.os.android){
			self.ConversationsControl.initialize();
			self.ContactsControl.initialize();
		}
		else {
			self.ContactsControl.sort();
			self.ConversationsControl.crossWithContacts();
			$(document).trigger('model:ready');
		}
		
		$(document).bind('backbutton',function(){
			$.ui.hideMenu();
			$.ui.goBack();
		});
		$(document).bind('menubutton',function(){
			$.ui.toggleMenu();
		});
	},
	showLoginForm : function(){
		$('#loginForm').show();
	},
	hideLoginForm : function(){
		$('#loginForm').hide();
	},
	toggleLoginForm : function(){
		$('#loginForm').toggle();
	},
	showProfileInfo : function(){
		$('#profileInfo').show();
	},
	hideProfileInfo : function(){
		$('#profileInfo').hide();
	},
	toggleProfileInfo : function(){
		$('#profileInfo').toggle();
	},
	checkConnection : function() {
		if((typeof navigator.network !== 'undefined') && (navigator.network !== null)){
			var networkState = navigator.connection.type;
			if(networkState === Connection.UNKNOWN || networkState === Connection.NONE){
				return false;
			}
			else {
				return true;
			}
		}
		return false;
	}
}

Handlebars.registerHelper('previewMsg', function(messages) {
	return messages[0].message;
});

Handlebars.registerHelper('getBubbleClass', function(user) {
	return (user&&user=="true")?"right-bubble":"left-bubble";
});
Handlebars.registerHelper('formatDate', function(date){
	return new Date(parseInt(date)).format('HH:mm dd MMM YY');
});
Handlebars.registerHelper('reverse-each', function(context, options) {
	var ret = "";

	for(var i=context.length-1, j=0; i>=j; i--) {
		ret = ret + options.fn(context[i]);
	}

	return ret;
});